package edu.cmu.cs.webapp.ioms.actions.order;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;

import edu.cmu.cs.webapp.ioms.dao.DataAccessException;
import edu.cmu.cs.webapp.ioms.dao.impl.ClientDAOImpl;
import edu.cmu.cs.webapp.ioms.logging.Alerts;
import edu.cmu.cs.webapp.ioms.models.Client;
import edu.cmu.cs.webapp.ioms.views.CustomersListView;

public class DeleteCustomerViewAction implements IViewActionDelegate {

	private CustomersListView _view;
	private Client _model;

	@Override
	public void init(IViewPart view) {
		this._view = (CustomersListView) view;
	}

	@Override
	public void run(IAction action) {
		if (this._model != null) {

			if (MessageDialog.openConfirm(this._view.getViewSite().getShell(),
					"Delete Confirmation",
					"Are you sure you want to delete this customer record?")) {
				try {
					new ClientDAOImpl().deleteClient(_model);
				} catch (DataAccessException e) {
					Alerts.getInstance().detailError("Data Access Error",
							e.getLocalizedMessage(), e);
				}
			}

			this._view.refreshCustomersView();
		}
	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		if (selection instanceof IStructuredSelection) {
			Object obj = ((IStructuredSelection) selection).getFirstElement();
			if (obj instanceof Client) {
				this._model = (Client) obj;
			}
		}
	}

}
